<!DOCTYPE html>
<html lang="zh-CN">
<!--浏览器搞笑标题-->
<script type="text/javascript" src="/js/FunnyTitle.js"></script>






<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/binblog/img/binblog.ico">
  <link rel="icon" type="image/png" href="/binblog/img/binblog.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="leo-bin">
  <meta name="keywords" content="">
  <title>多线程打印问题汇总 - 阿斌的个人博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/binblog/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/dracula.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/binblog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


<meta name="generator" content="Hexo 4.2.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/binblog/">&nbsp;<strong>Abin的Blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/binblog/img/6.webp') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-06-01 10:28">
      2020年6月1日 上午
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.3k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      28
       分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-post-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-post-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年7月15日 晚上
                
              </p>
            
            <article class="markdown-body">
              <h1 id="笔试常考之多线程顺序打印问题"><a href="#笔试常考之多线程顺序打印问题" class="headerlink" title="笔试常考之多线程顺序打印问题"></a>笔试常考之多线程顺序打印问题</h1><p><strong>题目类型描述：</strong></p>
<div class="hljs"><pre><code class="hljs tex">1.如何使用几个线程分别打印什么什么东西。
2.要求这几个线程一起运行，打印n次。
3.输出形如“什么什么什么....”的字符串。
4.总结就是按照顺序打印指定的结果。</code></pre></div>
<h2 id="前话（废话）"><a href="#前话（废话）" class="headerlink" title="前话（废话）"></a>前话（废话）</h2><p>这个题目类型是在我人生中第一个面试中遇到的 <code>╰(*°▽°*)╯</code>。</p>
<p>唉，说起这个眼泪就止不住的流了，因为我的第一次面试就给了阿里!</p>
<p>当时一面完之后，自我感觉良好，然后，然后就没有然后了。。。等了一个月都没有联系。。。</p>
<p>其实也是因为当时其实没有做好太多的准备，看到阿里的提前批就直接投了，没想到竟然直接约面了？</p>
<p>之后就临阵磨枪，竟然就刷到了同一类型的题目！</p>
<p>但是！关键就是当时，我，那个，看太快了！（太菜了）只是理解了怎么做。</p>
<p>然后巧的是，面试官问的是一道变种题！我当时还沾沾自喜，但是不知不觉中就说了一种很爆炸的做法！</p>
<p>我还不以为然。。。唉，现在回想起来，发现这个细节实在是太重要了。</p>
<p>所以这里将同类型题目进行一个总结！</p>
<p>也希望自己在即将到来的秋招取得一个满意的offer（拿不到offer我就要去考研了😔）</p>
<h2 id="信号量"><a href="#信号量" class="headerlink" title="信号量"></a>信号量</h2><p>这些题目我都是使用了一种叫做<code>信号量</code><strong>Semaphore</strong>的并发对象来实现的。</p>
<p>当然，还有很多其他的实现方式，我这里只讲这一种，我个人也是觉得设计的挺巧妙的。</p>
<p>Semaphore是一种基于Java并发框架AQS的并发工具类。</p>
<p>有兴趣的可以看看源码的实现，我这里讲相对于来说比较粗糙，只是便于个人理解。</p>
<p><strong>源码分析：</strong></p>
<div class="hljs"><pre><code class="hljs tex">作用：
1.Semaphopre里面有一个比较重要的概念叫做可用资源数，通过构造函数初始化，旨在控制线程的并发数。
2.当我们需要对某个场景进行限流的时候，信号量就派上用场了。
3.比如说我们的数据库连接池只有10个，但是同一时刻有30个线程需要操作数据库。
4.我们可以设置一个全局的信号量，初始化其中的资源数为10个。
5.每次获取数据库连接对象的时候都需要执行一次信号量中的acquire方法来获取可用资源。
6.acquire方法一旦判断出此时的资源数不为0，则代表当前线程拿到了一个资源数。
7.然后对资源数-1。
8.否则，当判断出资源数为0的时候说明现在没有可用资源了，当前线程就会阻塞。直到可用资源不为0为止。

原理个人理解：
1.因为信号量底层使用的是AQS，并直接使用AQS中的state值作为资源数。
2.所以一旦判断出state值不为0，就会执行-1操作，并直接返回。
3.但是一旦判断出state值为0，当前线程就会直接进入阻塞队列。
4.只有当state值再次大于0时，当前线程则会从阻塞队列中被唤醒。</code></pre></div>
<h2 id="题目一"><a href="#题目一" class="headerlink" title="题目一"></a>题目一</h2><div class="hljs"><pre><code class="hljs tex">1.使用三个线程分别打印A，B，C。
2.要求这三个线程一起运行，打印n次。
3.输出形如“ABCABCABC....”的字符串。</code></pre></div>
<h3 id="实现思路"><a href="#实现思路" class="headerlink" title="实现思路"></a>实现思路</h3><p>根据信号量的原理和用法，我们只需要设置三个信号量。</p>
<p>假设分别为A,B,C，他们的初始资源数分别为1，0，0。</p>
<p>没错，因为需要严格控制A,B,C的执行顺序，我们自然需要让A优先执行。</p>
<p>当B和C的初始资源数为0时，B和C的打印线程是无论如何都不会执行的。</p>
<p>除非有其他线程将B和C中的资源数进行修改！</p>
<p>没错，我们可以让A执行完毕之后就直接修改B的资源数，设为1就行。</p>
<p>然后B执行之后就修改C的资源数，也+1。</p>
<p>最后C执行完毕之后再次修改A的信号量，ok，完事！</p>
<p><strong>这就实现了控制线程的严格执行顺序的作用了。</strong></p>
<h3 id="实现代码"><a href="#实现代码" class="headerlink" title="实现代码"></a>实现代码</h3><div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PrintABCUsingSemaphore</span></span>&#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> times;
    <span class="hljs-keyword">private</span> Semaphore semaphoreA=<span class="hljs-keyword">new</span> Semaphore(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">private</span> Semaphore semaphoreB=<span class="hljs-keyword">new</span> Semaphore(<span class="hljs-number">0</span>);
    <span class="hljs-keyword">private</span> Semaphore semaphoreC=<span class="hljs-keyword">new</span> Semaphore(<span class="hljs-number">0</span>);
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PrintABCUsingSemaphore</span><span class="hljs-params">(<span class="hljs-keyword">int</span> times)</span></span>&#123;
        <span class="hljs-keyword">this</span>.times=times;
    &#125;
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printABC</span><span class="hljs-params">(String content)</span></span>&#123;
        <span class="hljs-keyword">if</span> (<span class="hljs-string">"A"</span>.equals(content)) &#123;
            print(content, semaphoreA, semaphoreB);
        &#125;
        <span class="hljs-keyword">if</span> (<span class="hljs-string">"B"</span>.equals(content)) &#123;
            print(content, semaphoreB, semaphoreC);
        &#125;
        <span class="hljs-keyword">if</span> (<span class="hljs-string">"C"</span>.equals(content)) &#123;
            print(content, semaphoreC, semaphoreA);
        &#125;
    &#125;
    
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(String content, Semaphore currentSemaphore, Semaphore nextSemaphore)</span> </span>&#123;
        <span class="hljs-keyword">try</span> &#123;
            <span class="hljs-comment">//开启循环打印</span>
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; times; i++) &#123;
                <span class="hljs-comment">//尝试获取信号量中的资源数,当资源数不为0，当前线程继续执行，否则，当前线程阻塞，一旦拿到资源，原始的资源数-1</span>
                currentSemaphore.acquire();
                System.out.println(content);
                <span class="hljs-comment">//当前线程执行完毕，将顺序的下一个信号量的资源数+1</span>
                nextSemaphore.release();
            &#125;
        &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;
            e.printStackTrace();
        &#125;
    &#125;
&#125;</code></pre></div>
<p><strong>测试代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
    PrintABCUsingSemaphore printABCUsingSemaphore = <span class="hljs-keyword">new</span> PrintABCUsingSemaphore(<span class="hljs-number">5</span>);
    <span class="hljs-comment">//启动线程1</span>
    <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() &#123;
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
            printABCUsingSemaphore.printABC(<span class="hljs-string">"A"</span>);
        &#125;
    &#125;).start();

    <span class="hljs-comment">//启动线程2</span>
    <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() &#123;
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
            printABCUsingSemaphore.printABC(<span class="hljs-string">"B"</span>);
        &#125;
    &#125;).start();

    <span class="hljs-comment">//启动线程3</span>
    <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() &#123;
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
            printABCUsingSemaphore.printABC(<span class="hljs-string">"C"</span>);
        &#125;
    &#125;).start();
&#125;</code></pre></div>
<p><strong>测试结果：</strong></p>
<p><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/image-20200715212016579.png" srcset="/binblog/img/loading.gif" alt="image-20200715212016579"></p>
<h2 id="题目二（阿里飞猪一面原题）"><a href="#题目二（阿里飞猪一面原题）" class="headerlink" title="题目二（阿里飞猪一面原题）"></a>题目二（阿里飞猪一面原题）</h2><div class="hljs"><pre><code class="hljs tex">1.现在有10个线程，同时启动这10个线程。
2.如何使用这10个线程按照顺序依次打印出12345678910。</code></pre></div>
<h3 id="实现思路-1"><a href="#实现思路-1" class="headerlink" title="实现思路"></a>实现思路</h3><p><strong>看了之前的思路和代码，我们可以照葫芦画瓢吗。</strong></p>
<p>那我们就分别设置10个信号量，然后像上面那面依次获取然后释放资源。</p>
<p>No No No，如果你也是这么想的话，那真是 <strong><code>too  young ，too native</code>！</strong></p>
<p>我第一次面试就是这么说的，说完还挺自信的，但是如果面试官要你开100线程呢？你也设100信号量？</p>
<p>有的时候我们不能想的太直接，太简单了，很显然，虽然设10个信号量可以实现，但是太low了！</p>
<p>那怎么做？</p>
<p>其实我们可以观察下需要打印的结果：<strong>12345678910</strong></p>
<p>不就是简单的阿拉伯数字吗？错！你还可以把它们当作两种数来看待：<code>奇数和偶数</code>！</p>
<p>所以我们其实只要设置两个信号量就可以破题了！分别是<code>奇数信号量</code>和<code>偶数信号量</code>！</p>
<p><strong>剩下的，就可以借鉴上面的实现套路啦！</strong></p>
<h3 id="实现代码-1"><a href="#实现代码-1" class="headerlink" title="实现代码"></a>实现代码</h3><div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PrintNumberUsingSemaphore</span></span>&#123;
    <span class="hljs-keyword">private</span> Semaphore oddSemaphore=<span class="hljs-keyword">new</span> Semaphore(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">private</span> Semaphore evenSemaphore=<span class="hljs-keyword">new</span> Semaphore(<span class="hljs-number">0</span>);
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printNumber</span><span class="hljs-params">(<span class="hljs-keyword">int</span> number)</span></span>&#123;
        <span class="hljs-keyword">if</span>((number&amp;<span class="hljs-number">1</span>)==<span class="hljs-number">1</span>)&#123;
            print(number,oddSemaphpore,evenSemaphore);
        &#125;<span class="hljs-keyword">else</span>&#123;
            print(number,evenSemaphore,oddSemaphore);
        &#125;
    &#125;
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-keyword">int</span> number,Semaphore currentSemaphore,Semaphore nextSemaphore)</span></span>&#123;
        <span class="hljs-keyword">try</span> &#123;
            currentSemaphore.acquire();
            System.out.println(number);
            nextSemaphore.release();
        &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;
            e.printStackTrace();
        &#125;
    &#125;
&#125;</code></pre></div>
<p><strong>测试代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
    PrintNumberUsingSemaphore printNumberUsingSemaphore = <span class="hljs-keyword">new</span> PrintNumberUsingSemaphore();
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">10</span>; i++) &#123;
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> number = i;
        <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() &#123;
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
                printNumberUsingSemaphore.isOddOrEven(number);
            &#125;
        &#125;).start();
    &#125;
&#125;</code></pre></div>
<p><strong>测试结果 ：</strong></p>
<p><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/image-20200715214046184.png" srcset="/binblog/img/loading.gif" alt="image-20200715214046184"></p>
<h2 id="题目三"><a href="#题目三" class="headerlink" title="题目三"></a>题目三</h2><div class="hljs"><pre><code class="hljs tex">1.给定正整数n
2.设计两个线程
3.A只打印奇数，B只打印偶数，要求顺序打印1~n</code></pre></div>
<h3 id="实现思路-2"><a href="#实现思路-2" class="headerlink" title="实现思路"></a>实现思路</h3><p>ok，在经过了前面两道题之后，相信这道题你一定是得心应手了吧！</p>
<p>具体思路和上面的一样，实现细节完全和题目要求有关，这里不详细说了。</p>
<h3 id="实现代码-2"><a href="#实现代码-2" class="headerlink" title="实现代码"></a>实现代码</h3><div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PrintOddAndEvenUsingSemaphore</span></span>&#123;
    <span class="hljs-keyword">private</span> Semaphore semaphoreOdd = <span class="hljs-keyword">new</span> Semaphore(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">private</span> Semaphore semaphoreEven = <span class="hljs-keyword">new</span> Semaphore(<span class="hljs-number">0</span>);

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printOddOrEven</span><span class="hljs-params">(<span class="hljs-keyword">int</span> number, String threadName)</span> </span>&#123;
        <span class="hljs-comment">//为奇数才打印</span>
        <span class="hljs-keyword">if</span> ((number &amp; <span class="hljs-number">1</span>) == <span class="hljs-number">1</span>) &#123;
            print(number, semaphoreOdd, semaphoreEven, threadName);
        &#125; <span class="hljs-keyword">else</span> &#123;
            print(number, semaphoreEven, semaphoreOdd, threadName);
        &#125;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-keyword">int</span> number, Semaphore currentSemaphore, Semaphore nextSemaphore, String threadName)</span> </span>&#123;
        <span class="hljs-keyword">try</span> &#123;
            <span class="hljs-comment">//抢当前的资源数,拿到的资源数为1，成功抢到，0代表没抢到，当前线程阻塞</span>
            currentSemaphore.acquire();
            System.out.println(<span class="hljs-string">"当前线程是："</span> + threadName + <span class="hljs-string">"打印结果是："</span> + number);
            <span class="hljs-comment">//当前线程执行完毕，释放下一个信号量的资源数</span>
            nextSemaphore.release();
        &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;
            e.printStackTrace();
        &#125;
    &#125;
&#125;</code></pre></div>
<p><strong>测试代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
    <span class="hljs-keyword">int</span> n = <span class="hljs-number">9</span>;
    PrintOddAndEvenUsingSemaphore printOddAndEvenUsingSemaphore = <span class="hljs-keyword">new</span> PrintOddAndEvenUsingSemaphore();
    <span class="hljs-comment">//开启A线程</span>
    <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() &#123;
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= n; i++) &#123;
                <span class="hljs-keyword">if</span> ((i &amp; <span class="hljs-number">1</span>) == <span class="hljs-number">1</span>) &#123;
                    printOddAndEvenUsingSemaphore.printOddOrEven(i, Thread.currentThread().getName());
                &#125;
            &#125;
        &#125;
    &#125;).start();

    <span class="hljs-comment">//开启线程B</span>
    <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() &#123;
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= n; i++) &#123;
                <span class="hljs-keyword">if</span> ((i &amp; <span class="hljs-number">1</span>) == <span class="hljs-number">0</span>) &#123;
                    printOddAndEvenUsingSemaphore.printOddOrEven(i, Thread.currentThread().getName());
                &#125;
            &#125;
        &#125;
    &#125;).start();
&#125;</code></pre></div>
<p><strong>测试结果：</strong></p>
<p><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/image-20200715215257404.png" srcset="/binblog/img/loading.gif" alt="image-20200715215257404"></p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p><strong>ok,终于写完啦！累的一批。。。</strong></p>
<p><strong>今天就肝这一篇文章了，其他的明天在肝。</strong></p>
<p><strong>遇到这种多线程打印问题其实还有很多方法实现，信号量也只是一种方法。</strong></p>
<p><strong>但是学完之后有没有感觉又get到一个新技能了？哈哈，我当时也是这样子的。</strong></p>
<p><strong>学无止境，我们秋招加油！</strong></p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/binblog/categories/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%92%8C%E5%B9%B6%E5%8F%91/">多线程和并发</a>
                    
                  </div>
                
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/binblog/2020/06/01/%E6%88%91%E7%88%B6%E6%AF%8D%E4%B9%8B%E9%97%B4%E7%9A%84%E7%88%B1%E6%83%85/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">我父母之间的爱情</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/binblog/2020/05/31/%E4%B8%BA%E4%BB%80%E4%B9%88%E7%B3%BB%E5%88%97%E4%B9%8B%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E4%BD%BF%E7%94%A8MQ%EF%BC%9F/">
                        <span class="hidden-mobile">为什么系列之为什么要使用MQ？</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script defer src="https://cdn.staticfile.org/valine/1.4.14/Valine.min.js" ></script>

  <script type="text/javascript">
    var oldLoadVa = window.onload;
    window.onload = function () {
      oldLoadVa && oldLoadVa();

      new Valine({
        el: "#vcomments",
        app_id: "vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz",
        app_key: "v2hMMe4Mzz3mqpy9jwd7qx8B",
        placeholder: "说点什么吧！",
        path: window.location.pathname,
        avatar: "retro",
        meta: ["nick","mail","link"],
        pageSize: "10",
        lang: "zh-CN",
        highlight: true,
        recordIP: false,
        serverURLs: "",
      });
    };
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


    
  <!-- 备案信息 -->
  <div class="beian">
    <a href="http://beian.miit.gov.cn/" target="_blank"
       rel="nofollow noopener">京ICP证123456号</a>
    
      <a
        href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
        rel="nofollow noopener"
        class="beian-police"
        target="_blank"
      >
        <span class="beian-police-sep">&nbsp;|&nbsp;</span>
        
          <img src="/binblog/img/police_beian.png" srcset="/binblog/img/loading.gif" alt="police-icon" />
        
        <span>京公网安备12345678号</span>
      </a>
     
  </div>


    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/binblog/js/debouncer.js" ></script>
<script  src="/binblog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/binblog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/binblog/js/clipboard-use.js" ></script>



  <script defer>
  (function () {
    // 查询存储的记录
    function getRecord(Counter, target) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({target})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {target, time: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    }

    // 发起自增请求
    function increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    }

    // 构建自增请求体
    function buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "time": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    }

    // 校验是否为有效的 UV
    function validUV() {
      var key = 'LeanCloud_UV_Flag';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    }

    function addCount(Counter) {
      var enableIncr = 'true' === 'true' && window.location.hostname !== 'localhost';
      var getterArr = [];
      var incrArr = [];

      // 请求 PV 并自增
      var pvCtn = document.querySelector('#leancloud-site-pv-container');
      if (pvCtn || enableIncr) {
        var pvGetter = getRecord(Counter, 'site-pv').then((record) => {
          incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-pv');
          if (ele) {
            ele.innerText = record.time + 1;
            if (pvCtn) {
              pvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#leancloud-site-uv-container');
      if (uvCtn || enableIncr) {
        var uvGetter = getRecord(Counter, 'site-uv').then((record) => {
          var vuv = validUV();
          vuv && incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-uv');
          if (ele) {
            ele.innerText = record.time + (vuv ? 1 : 0);
            if (uvCtn) {
              uvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(uvGetter);
      }

      // 如果是文章，请求文章的浏览数，并自增
      if ('true' === 'true') {
        var viewCtn = document.querySelector('#leancloud-post-views-container');
        if (viewCtn || enableIncr) {
          var target = decodeURI('/binblog/2020/06/01/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%89%93%E5%8D%B0%E9%97%AE%E9%A2%98%E6%B1%87%E6%80%BB/');
          var viewGetter = getRecord(Counter, target).then((record) => {
            incrArr.push(buildIncrement(record.objectId))
            if (viewCtn) {
              var ele = document.querySelector('#leancloud-post-views');
              if (ele) {
                ele.innerText = (record.time || 0) + 1;
                viewCtn.style.display = 'inline';
              }
            }
          });
          getterArr.push(viewGetter);
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && increment(Counter, incrArr);
        })
      }
    }

    var app_id = 'vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz'
    var app_key = 'v2hMMe4Mzz3mqpy9jwd7qx8B'
    var server_url = ''

    function fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': app_id,
            'X-LC-Key': app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };

      addCount(Counter);
    }

    var api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${ app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;

    if (api_server) {
      fetchData(api_server);
    } else {
      fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
        .then(resp => resp.json())
        .then(({api_server}) => {
          fetchData('https://' + api_server);
        });
    }
  })();
</script>






  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "多线程打印问题汇总&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/binblog/js/local-search.js" ></script>
  <script>
    var path = "/binblog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  













  

  

  

  

  

  





<script src="/binblog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/binblog/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
